<?php

declare (strict_types=1);

namespace App\Common\Model\Admin;

use Hyperf\Database\Model\Relations\HasOne;
use Zms\Basics\BasicsModel;
use Zms\HyperfCasts\{IpCasts, StrtotimeCasts};
use Zms\Unit\Json;

/**
 * @property int $id
 * @property string $name 访问名称
 * @property string $callback 方法
 * @property string $method 请求方式
 * @property string $url 访问地址
 * @property string $param GET参数
 * @property string $ip IP
 * @property int $status 操作状态
 * @property string $msg 操作结果
 * @property string $ascription IP属地
 * @property int $user_id 操作人员
 * @property string $os 操作系统
 * @property string $browser 浏览器
 * @property string $guard 角色
 * @property string $app Sys
 * @property int $time 时间
 */
class LogModel extends BasicsModel
{
    public bool $timestamps = false;
    /**
     * The table associated with the model.
     *
     * @var ?string
     */
    protected ?string $table = 'admin_log';
    /**
     * The attributes that are mass assignable.
     *
     * @var array
     */
    protected array $fillable = [];
    /**
     * The attributes that should be cast to native types.
     *
     * @var array
     */
    protected array $casts = [
        'id' => 'int',
        'user_id' => 'integer',
        'status' => 'integer',
        'ip' => IpCasts::class,
        'time' => StrtotimeCasts::class,
    ];


    /**
     * 关联操作员
     * @return HasOne
     */
    public function user(): HasOne
    {
        return $this->hasOne(UserModel::class, 'id', 'user_id');
    }


    /**
     * 设置参数记录
     * @param $value
     */
    public function setParamAttribute($value): void
    {
        $this->attributes['param'] = Json::encode([]);
        if (is_array($value)) {
            $data = Json::encode($value, JSON_UNESCAPED_UNICODE);
            if (mb_strlen($data) <= 1000) {
                $this->attributes['param'] = $data;
            } else {
                $this->attributes['param'] = Json::encode(['参数过多,已跳过记录'], JSON_UNESCAPED_UNICODE);
            }
        }
    }


    /**
     * 获取参数记录
     * @param $vaue
     * @return array
     */
    public function getParamAttribute($vaue): array
    {
        return $vaue ? Json::decode($vaue) : [];
    }
}
